package com.hx.update.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;

import com.android.base.util.Mmkv;
import com.android.base.util.ToastUtil;
import com.dq.ad.UMManager;
import com.hx.update.UpdateInfo;
import com.hx.update.dialog.UpdateDialog;

import java.io.File;

public class UpdateUtil {

    public static int getPackageVersionCode(Context context) {
        int version = 0;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            version = pi.versionCode;
        } catch (Exception e) {
            //
        }
        return version;
    }

    public static Uri getFileUriIn(Context context, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(context, context.getPackageName() + ".update.provider", file);
        }
        return Uri.fromFile(file);
    }

    public static void install(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        Uri uri = getFileUriIn(context, file);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static int getIgnoreVersion() {
        return Mmkv.getInteger("ignore_version");
    }

    public static void setIgnoreVersion(int ignoreVersion) {
        Mmkv.setInteger("ignore_version", ignoreVersion);
    }

    public static void checkUpdate(final Context context, final UpdateInfo updateInfo, final boolean isManual) {
        checkUpdate(context, updateInfo, isManual, null);
    }

    public static void checkUpdate(final Context context, final UpdateInfo updateInfo, final OnUpdateCallback callback) {
        checkUpdate(context, updateInfo, false, callback);
    }

    public static void checkUpdate(final Context context, final UpdateInfo updateInfo, final boolean isManual, final OnUpdateCallback callback) {
        if (updateInfo.apkVersion > getPackageVersionCode(context) && (updateInfo.apkVersion != getIgnoreVersion() || isManual)) {
            UpdateDialog updateDialog = new UpdateDialog(context);
            updateDialog.setApkVersion(updateInfo.apkVersionStr);
            updateDialog.setApkSize(updateInfo.apkSize);
            updateDialog.setApkStatus(updateInfo.apkStatus);
            updateDialog.setClickListener(new UpdateDialog.UpdateDialogListener() {
                @Override
                public void onUpgrade() {
                    UMManager.onEvent(UMManager.Event.update_Download);
                    // 更新操作
                    HProgressDialogUtil.showHorizontalProgressDialog(context, "下载进度", true);
                    HProgressDialogUtil.setMax(updateInfo.apkSize);
                    DownloadUtil.getInstance().download(updateInfo.apkUrl, context.getExternalCacheDir() + File.separator, new DownloadUtil.DownloadListener() {
                        @Override
                        public void onDownloadSuccess(String path) {
                            UMManager.onEvent(UMManager.Event.update_DownloadSucceed);
                            install(context, new File(path));
                            HProgressDialogUtil.dismissDialog();
                        }

                        @Override
                        public void onDownloading(long progress) {
                            HProgressDialogUtil.setProgress(progress);
                        }

                        @Override
                        public void onDownloadFailed(String err) {
                            ToastUtil.showShortToastCenter(context, err);
                            HProgressDialogUtil.dismissDialog();
                            checkUpdate(context, updateInfo, isManual, callback);
                        }
                    });
                }

                @Override
                public void onIgnore() {
                    // 忽略此版本更新
                    UMManager.onEvent(UMManager.Event.update_ignore);
                    setIgnoreVersion(updateInfo.apkVersion);
                    if (callback != null) {
                        callback.onCancel();
                    }
                }

                @Override
                public void onClose() {
                    if (callback != null) {
                        callback.onCancel();
                    }
                }
            });
            updateDialog.show();
        } else {
            if (isManual) {
                ToastUtil.showShortToastCenter(context, "已经是最新版本了");
            }
            if (callback != null) {
                callback.onCancel();
            }
        }
    }

    public interface OnUpdateCallback {
        void onCancel();
    }
}
